package com.example.yskjproject.view;

import static androidx.core.content.ContextCompat.getSystemService;

import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.SweepGradient;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;

import androidx.core.content.ContextCompat;

import com.example.yskjproject.R;
import com.example.yskjproject.utils.LogUtils;

public class HalfCircleProgressView extends View {

    private Paint paint;
    private RectF oval;
    private float leftProgress = 0f;
    private float rightProgress = 0f;
    private int maxProgress = 100;
    private int currentProgress = 0;
    private Paint paintLeft;
    private Paint paintRight;
    private int outerRadiusPx;
    private int innerRadiusPx;
    private int strokeWidthPx;
    private SweepGradient mGradient;
    private Paint shadowPaint;
    private int screenWidth = 0;
    private int strokeWidth = 0;
    private ValueAnimator leftProgressAnimator;
    private ValueAnimator rightProgressAnimator;


    public HalfCircleProgressView(Context context) {
        super(context);
        init();
        setLayerType(LAYER_TYPE_SOFTWARE, null);

    }

    public HalfCircleProgressView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public HalfCircleProgressView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        DisplayMetrics displayMetrics = new DisplayMetrics();
        WindowManager windowManager = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
        windowManager.getDefaultDisplay().getMetrics(displayMetrics);

        screenWidth = displayMetrics.widthPixels;
        LogUtils.d("HalfCircleProgressView:::" + "Width: " + screenWidth + ", Height: " + screenWidth);
        // 外圆半径和内圆半径
        // 外圆半径和内圆半径
        final int outerRadiusDp;
        final int innerRadiusDp;
        final int shadowWidth;
        if (screenWidth > 3000) {
            strokeWidth = 64;
            outerRadiusDp = 516;
            innerRadiusDp = 490;
            shadowWidth = 35;
        } else {
            strokeWidth = 32;
            outerRadiusDp = 258;
            innerRadiusDp = 245;
            shadowWidth = 10;
        }
        int[] colors = {
                ContextCompat.getColor(getContext(), R.color.progress_gradient_1),
                ContextCompat.getColor(getContext(), R.color.progress_gradient_2),
                ContextCompat.getColor(getContext(), R.color.progress_gradient_3)
        };
        float[] positions = {0f, 0.5f, 1f};
        mGradient = new SweepGradient(getWidth() / 2f, getHeight() / 2f, colors, positions);
        setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        setWillNotDraw(false);
        paint = new Paint();
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeWidth(strokeWidth);
        paint.setAntiAlias(true);

        paintLeft = new Paint();
        paintLeft.setStyle(Paint.Style.STROKE);
        paintLeft.setStrokeWidth(strokeWidth);
        paintLeft.setAntiAlias(true);
        paintLeft.setStrokeCap(Paint.Cap.ROUND);

        paintRight = new Paint();
        paintRight.setStyle(Paint.Style.STROKE);
        paintRight.setStrokeWidth(strokeWidth);
        paintRight.setAntiAlias(true);
        paintRight.setStrokeCap(Paint.Cap.ROUND);

        shadowPaint = new Paint();
        shadowPaint.setStyle(Paint.Style.STROKE);
        shadowPaint.setStrokeWidth(shadowWidth);
        shadowPaint.setAntiAlias(true);


        // 将dp转换为px
        outerRadiusPx = dpToPx(outerRadiusDp);
        innerRadiusPx = dpToPx(innerRadiusDp);
        strokeWidthPx = dpToPx(strokeWidth);

        // 计算oval的尺寸，考虑到内外圆的半径和画笔的宽度
        int halfStroke = strokeWidthPx / 2;
        int width = outerRadiusPx * 2;
        int height = outerRadiusPx * 2;

        // 初始化oval，考虑到屏幕中心位置和底部对齐
        // 注意：这里使用getWidth()和getHeight()是为了适应不同屏幕尺寸
        // 半径加上画笔宽度的一半，确保圆形完整显示
        oval = new RectF(
                halfStroke, // 左边距
                getHeight() - height , // 上边距，底部对齐
                getWidth() - halfStroke, // 右边距
                getHeight() - halfStroke // 下边距，底部对齐
        );
        // 初始化动画
        leftProgressAnimator = ValueAnimator.ofFloat(leftProgress, leftProgress);
        leftProgressAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                leftProgress = (float) animation.getAnimatedValue();
                invalidate();
            }
        });

        rightProgressAnimator = ValueAnimator.ofFloat(rightProgress, rightProgress);
        rightProgressAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                rightProgress = (float) animation.getAnimatedValue();
                invalidate();
            }
        });
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);

        int desiredWidth;
        int desiredHeight;

        // 根据外圆半径和画笔宽度计算所需宽度
        final int outerRadiusDp;
        final int innerRadiusDp;
        final int strokeWidth;
        // 外圆半径和内圆半径
        if (screenWidth > 3000) {
            strokeWidth = 64;
            outerRadiusDp = 516;
            innerRadiusDp = 490;
        } else {
            strokeWidth = 32;
            outerRadiusDp = 258;
            innerRadiusDp = 245;
        }

        final int outerRadiusPx = dpToPx(outerRadiusDp);
        final int strokeWidthPx = dpToPx(strokeWidth);
        int halfStroke = strokeWidthPx / 2;
        desiredWidth = outerRadiusPx * 2;

        // 高度等于外圆直径加上画笔宽度的一半，以确保半圆完整显示
        desiredHeight = outerRadiusPx * 2 + halfStroke;

        if (widthMode == MeasureSpec.EXACTLY) {
            // 如果宽度模式是EXACTLY，那么使用指定的宽度
            desiredWidth = widthSize;
        } else {
            // 否则，使用我们计算出的宽度
            desiredWidth = desiredWidth + getPaddingLeft() + getPaddingRight();
        }

        if (heightMode == MeasureSpec.EXACTLY) {
            // 如果高度模式是EXACTLY，那么使用指定的高度
            desiredHeight = heightSize;
        } else {
            // 否则，使用我们计算出的高度
            desiredHeight = desiredHeight + getPaddingTop() + getPaddingBottom();
        }

        setMeasuredDimension(desiredWidth, desiredHeight);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        final int outerRadiusDp;
        final int innerRadiusDp;
        final int strokeWidth;
        // 外圆半径和内圆半径
        if (screenWidth > 3000) {
            strokeWidth = 64;
            outerRadiusDp = 516;
            innerRadiusDp = 490;
        } else {
            strokeWidth = 32;
            outerRadiusDp = 258;
            innerRadiusDp = 245;
        }

        // 将dp转换为px
        outerRadiusPx = dpToPx(outerRadiusDp);
        innerRadiusPx = dpToPx(innerRadiusDp);
        strokeWidthPx = dpToPx(strokeWidth);

        // 计算oval的尺寸，考虑到内外圆的半径和画笔的宽度
        int halfStroke = strokeWidthPx / 2;
        int width = outerRadiusPx * 2;
        int height = outerRadiusPx * 2;

        // 初始化oval，考虑到屏幕中心位置和底部对齐
        // 半径加上画笔宽度的一半，确保圆形完整显示
        oval.set(
                halfStroke, // 左边距
                h - height, // 上边距，底部对齐
                w - halfStroke, // 右边距
                h - halfStroke // 下边距，底部对齐
        );
    }


    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        Matrix matrix = new Matrix();
        matrix.setRotate(90, canvas.getWidth() / 2, canvas.getHeight() / 2);
        mGradient.setLocalMatrix(matrix);
        paintLeft.setShader(mGradient);
        paintRight.setShader(mGradient);
        // 创建用于填充圆形区域的Paint对象
        Paint fillPaint = new Paint();
        fillPaint.setColor(Color.WHITE);
        fillPaint.setStyle(Paint.Style.FILL);
        fillPaint.setAntiAlias(true);
        RectF shadowOval = new RectF(oval);
        float shadowRadius = 12f; // 阴影模糊半径
        // 扩展shadowOval，使其比oval稍大，以容纳阴影
        shadowOval.inset(-shadowRadius, -shadowRadius);

        // 绘制白色填充圆形
        canvas.drawOval(oval, fillPaint);
        // 绘制背景半圆
        paint.setColor(ContextCompat.getColor(getContext(), R.color.circle_radio_color));
        shadowPaint.setAlpha(0);
        // 半圆背景阴影
        shadowPaint.setShadowLayer(shadowRadius, 0f, 0f, ContextCompat.getColor(getContext(), R.color.btn_bg2));

        // 绘制带有阴影效果的透明半圆
        canvas.drawArc(shadowOval, -180, 180, false, shadowPaint);
        canvas.drawArc(oval, -180, 180, false, paint);
        // 绘制进度左半圆
        canvas.drawArc(oval, -180, (leftProgress * 90) / maxProgress, false, paintLeft);
        //绘制进度右半圆
        canvas.drawArc(oval, 0, -(rightProgress * 90) / maxProgress, false, paintRight);
    }

    public void setLeftProgress(int progress) {
        if (progress != leftProgress) {
            leftProgressAnimator.cancel(); // 取消之前的动画
            leftProgressAnimator.setFloatValues(leftProgress, Math.max(0, Math.min(progress, maxProgress)));
            leftProgressAnimator.setDuration(200); // 设置动画持续时间
            leftProgressAnimator.start();
        }
    }

    public void setRightProgress(int progress) {
        if (progress != rightProgress) {
            rightProgressAnimator.cancel(); // 取消之前的动画
            rightProgressAnimator.setFloatValues(rightProgress, Math.max(0, Math.min(progress, maxProgress)));
            rightProgressAnimator.setDuration(200); // 设置动画持续时间
            rightProgressAnimator.start();
        }
    }

    // 添加dp转换为px的方法
    private int dpToPx(int dp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics());
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                return true;
            default:
                return super.onTouchEvent(event);
        }
    }
}
